import React from 'react'
import {Row, Col, Button, Table, Select, Modal, message} from 'antd'
import '../styles.css'
import Model from "./Model"
import axios from "axios";
import api from "../../../api/api";
import Addcompany from "../CompanyManagement/Addcompany";

const {Option} = Select;


class DepartmentManagement extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modelData: {
                title: "新增公司",
                visible: false,
                type: 1,//1:新增部门, 2:编辑,  3:新增子部门
                gridList: {}
            },
            thirdFactoryId: "",
            DepartmentList: [],//部门列表数据
            DepartmentInfo: "",
            gid: "",
            pageNum: 1,
            pageSize: 10,
            total: 0
        };
    }

    componentDidMount() {
        console.log("初始化页面");
        this.getDepartmentManageList();
        this.companyChange();
    }

    columns = [
        {
            title: '部门编码',
            dataIndex: 'code',
            key: 'code',
            width: '20%'
        },
        {
            title: '部门名称',
            dataIndex: 'fullName',
            key: 'fullName',
            width: '30%'
        },
        {
            title: '部门简称',
            dataIndex: 'name',
            width: '10%',
            key: 'name'
        },
        {
            title: '更新时间',
            dataIndex: 'createTime',
            width: '20%',
            key: 'createTime'
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '20%',
            key: 'option',
            render: (_ext, record, Item) => {
                return (
                    <span>
            <a className="optionMargin" onClick={() => this.onClickAdd(record)}>添加子部门</a>
            <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
            {/*<a className="optionMargin"*/}
               {/*onClick={() => this.onClickguikou(record.departmentId, record.guiKouFlag)}>{record.guiKouFlag == 1 ? "设为归口部门" : "设为非归口部门"}</a>*/}
            <a className="optionMargin" onClick={() => this.onClickDelete(record.departmentId, record.code)}>删除</a>
          </span>
                )
            }
        }
    ];

    //加载页面数据
    getDepartmentManageList() {
        var that = this;
        let url = "";
        let tempCompanyid = "";
        if (that.state.thirdFactoryId === undefined) {
            that.state.thirdFactoryId = ""
        }
        if (that.state.selectCompanyId === undefined) {
            that.tempCompanyid = that.state.selectCompanyId;
            that.state.selectCompanyId = "";
        }
        url = api.api_URL + "/admin/dept/queryAllDepartmentInfoByThirdFactoryIdForSelectS?pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize +
            "&thirdFactoryId=" + that.state.thirdFactoryId + "&orgCode=" + localStorage.getItem('orgCode') + "&gid=" + that.state.selectCompanyId;
        if (that.state.selectCompanyId === "") {
            that.setState({
                selectCompanyId: that.tempCompanyid
            })
        }
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                message.error({content: "加载失败,请重新尝试！"})
                return;
            }
            let resp = res.data.data.departmentInfoList;
            that.setState({
                DepartmentList: resp.content,
                total: resp.totalSize
            })
        }).catch(function (err) {
            console.log(err);
            message.error({content: "加载失败,请重新尝试！"})

        });
    }

    //分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getDepartmentManageList()
        });
    }

    //新增子部门
    onClickAdd(item) {
        this.setState({
            modelData: {
                title: "新增子部门",
                type: 3,
                visible: true,
                gridList: item,
                isParent: false
            }
        }, () => {
            this.child.clearData()
        });
    }

    //编辑部门
    onClickEdit(item) {
        this.setState({
            modelData: {
                title: "编辑",
                type: 2,
                visible: true,
                gridList: item,
                isParent: false
            }
        }, () => {
            this.child.initEditData()
        });
    }

    //新增部门
    addcompany(item) {
        this.setState({
            modelData: {
                title: "新增部门",
                type: 1,
                visible: true,
                isParent: true
            }
        }, () => {
            this.child.clearData()
        });
    }

    //设置为归属部门
    onClickguikou(departmentId, guiKouFlag) {
        const that = this
        let url = api.api_URL + "/admin/dept/departmentInfoGuiKouFlag?&guiKouFlag=" + guiKouFlag + "&departmentId=" + departmentId;
        axios({
            method: 'POST',
            url: url,
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": "application/json;charset=UTF-8"
            },
        }).then(function (res) {
            if (res.data.data.department != 1) {
                message.error({content: "设置失败,请重新尝试！"})
                return
            }
            message.success({content: "设置成功！"})

            that.getDepartmentManageList()
        }).catch(function (error) {
            console.log(error);
            message.error({content: "设置失败,请重新尝试！"})
        })
    }

    //删除
    onClickDelete(departmentId, code) {
        let that = this;
        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/admin/dept/deleteDepartmentInfo?departmentInfoId=" + departmentId + "&code=" + code;
                    axios({
                        method: 'POST',
                        url: url,
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": "application/json;charset=UTF-8"
                        },
                    }).then(function (res) {
                        if (res.data.data.code != 1) {
                            message.error({content: "删除失败,请重新尝试！"})
                            return
                        }
                        that.getDepartmentManageList()
                        message.success({content: "删除成功！"})
                        configModel.destroy();
                    }).catch(function (error) {
                        console.log(error);
                        message.error({content: "删除失败,请重新尝试！"})

                    })
                }).catch((e) => console.warn(e));
            },
            onCancel() {
            },
        })
    }

    //确定
    handleOk = e => {
        console.log(e);
        this.setState({
            visible: false,
        });
    };

    handleCancel = e => {
        console.log(e);
        this.setState({
            visible: false,
        });
    };

    //搜索
    onclickSearch() {
        console.info("搜索");
        this.getDepartmentManageList();
    }

    //重置
    onclickReset() {
        let that = this;
        console.info('重置')
        this.setState({
            selectCompanyId: undefined,
            selectFactoryId: undefined,
        }, () => {
            that.state.thirdFactoryId = "";
            this.getDepartmentManageList()
        });

    };

    //获取公司下拉框值
    companySelect = [];

    getCompanySelect() {
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/admin/company/queryAllCompanyInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                message.error({content: "删除失败,请重新尝试！"})
                return;
            }
            let companyInfoList = res.data.data.companyInfoList;
            for (let i = 0; i < companyInfoList.length; i++) {
                let comData = companyInfoList[i];
                const data = {};
                data.key = comData.thirdCompanyId;
                data.label = comData.companyName;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.companySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }

        }).catch(function (err) {
            console.log(err);
            message.error({content: "删除失败,请重新尝试！"})

        })

    }

    //获取厂区下拉框值
    factorySelect = [];

    //选择公司
    companyChange = () => {
        this.factorySelect = [];
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/admin/factory/queryFactoryInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                message.error({content: "加载失败,请重新尝试！"})
                return;
            }
            let factoryInfoList = res.data.data.factoryInfoList;
            if (factoryInfoList.length <= 0) {
                console.log("没有厂房数据")
                return;
            }
            for (let i = 0; i < factoryInfoList.length; i++) {
                let facData = factoryInfoList[i];
                const data = {};
                data.key = facData.thirdFactoryId;
                data.label = facData.name;
                console.log(data)
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.factorySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }

        }).catch(function (err) {
            console.log(err);
            message.error({content: "加载失败,请重新尝试！"})
        })
    }
    factoryChange = (value) => {
        this.setState({
            thirdFactoryId: value,
            selectFactoryId: value,
        })
    }


    onRef = (ref) => {
        this.child = ref
    }
    handleCancel = e => {
        this.setState({
            modelData: {
                visible: false
            },
        }, () => {
            this.refresh()
        });
    }

    //刷新
    refresh() {
        this.getDepartmentManageList()
    }

    //下载
    downloadClick = () => {
        let that = this;
        if (that.state.thirdFactoryId == "") {
            alert("请选择厂区和公司！");
            return
        }
        let exportUrl = api.api_URL + "/admin/dept/downDepartmentInfoExcel?thirdFactoryId=" + that.state.thirdFactoryId;
        that.exportFile(exportUrl)
    }

    exportFile(url, data) {
        axios({
            method: 'post',
            url: url,
            responseType: 'blob'
        }).then((res) => {
            const content = res.data;
            const blob = new Blob([content]);
            const fileName = "部门导出数据.xls";
            const selfURL = window[window.webkitURL ? 'webkitURL' : 'URL'];
            let elink = document.createElement('a');
            if ('download' in elink) {
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = selfURL['createObjectURL'](blob);
                document.body.appendChild(elink);

                // 触发链接
                elink.click();
                selfURL.revokeObjectURL(elink.href);
                document.body.removeChild(elink)
            } else {
                navigator.msSaveBlob(blob, fileName);
            }
        })
    }


    render() {

        return (
            <div className="girdBg">
                <Row className="searchBox">
                    <Col span={12}>
                        {/*<Select placeholder="请选择公司" style={{width: 200}} onChange={this.companyChange}  allowClear*/}
                                {/*value={this.state.selectCompanyId}>*/}
                            {/*{this.companySelect}*/}
                        {/*</Select>*/}
                        <Select showSearch={true} optionFilterProp="children" placeholder="请选择公司" style={{width: 200, marginLeft: 30}} onChange={this.factoryChange}
                                 allowClear  value={this.state.selectFactoryId}>
                            {this.factorySelect}
                        </Select>
                        <Button icon={"search"} type='primary' style={{marginLeft: 30}}
                                onClick={this.onclickSearch.bind(this)}>搜索</Button>
                        <Button style={{marginLeft: 30}} onClick={this.onclickReset.bind(this)}>重置</Button>
                    </Col>
                    <Col span={12} className="btnRight">
                        <Button icon={"save"} type='primary' onClick={this.addcompany.bind(this)}>新增部门</Button>
                        {/*<Button shape='circle' type='primary' icon="download" onClick={this.downloadClick}/>*/}
                    </Col>
                </Row>
                <Row style={{margin: 30}}>
                    <Table
                        columns={this.columns}
                        dataSource={this.state.DepartmentList}
                        scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                        columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                            const fun = () => ({style: {whiteSpace: 'nowrap'}});
                            item.onHeaderCell = fun;
                            item.onCell = fun;
                            return item;
                        })}
                        pagination={{
                            simple: false,
                            current: this.state.pageNum,
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            showTotal: (count = this.state.total) => {
                                return '共' + count + '条'
                            },
                            onChange: (current, pageSize) => {
                                this.onBaseClick(current, pageSize)
                            }
                        }}
                    />
                </Row>
                <Model data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                       onRef={this.onRef} history={this.props.history}/>
            </div>
        )
    }
}

export default DepartmentManagement